package com.huawei.app.demo.adapter;

import java.util.List;
import java.util.Map;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.TextView;

import com.huawei.app.demo.R;
import com.huawei.app.demo.util.LogUtils;
import com.huawei.app.httpapi.HttpApiResult;
import com.huawei.app.httpapi.IdeaHubHttpApiUtils;
import com.huawei.app.httpapi.ThreadPools;

/**
 * 通讯录ListView适配器
 *
 * @since 2021-01-23
 */
public class ContactAdapter extends BaseAdapter {

    private static final String TAG = ContactAdapter.class.getSimpleName();
    private LayoutInflater inflater;
    private List<Map<String,String>> itemList;

    public ContactAdapter(Context context, List<Map<String,String>> itemList){
        this.inflater = LayoutInflater.from(context);
        this.itemList = itemList;
    }

    @Override
    public int getCount() {
        return itemList.size();
    }

    @Override
    public Object getItem(int position) {
        return itemList.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        if (convertView == null) {
            convertView = inflater.inflate(R.layout.conference_contact_item, null);
        }
        TextView contactName = convertView.findViewById(R.id.contactName);
        TextView contactNumber = convertView.findViewById(R.id.contactNumber);
        Button callBtn = convertView.findViewById(R.id.contactCallBtn);

        contactName.setText(itemList.get(position).get("contactName"));
        contactNumber.setText(itemList.get(position).get("contactNumber"));
        callBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final String number = itemList.get(position).get("contactNumber");
                ThreadPools.run(new Runnable() {
                    @Override
                    public void run() {
                        HttpApiResult apiResult = IdeaHubHttpApiUtils.getInstance().callNumber(number);
                        if (!apiResult.isSuccess()) {
                            LogUtils.getInstance().e(TAG, "callNumber failed, apiResult is " + apiResult);
                        }
                    }
                });
            }
        });
        return convertView;
    }
}
